import grails.util.GrailsUtil
import com.portico.dept.solarch.*
import com.portico.security.Authority;
import com.portico.security.User;
import com.portico.security.UserAuthority;

import org.apache.commons.logging.LogFactory
import org.apache.commons.logging.Log
import com.portico.security.Requestmap

class BootStrap {

  Log logger = LogFactory.getLog("BootStrap")

  def init = { servletContext ->

    logger.info("Set up environment ${GrailsUtil.environment}")

    switch (GrailsUtil.environment) {
      case "development":
        logger.info("---> ${GrailsUtil.environment}")
        globalSetup();

        // Add a project
        def doDevSetup = { pname ->
          Project pr = Project.findByName(pname);
          if (pr == null) {
            pr = new Project(name: pname, projectType: "Internal", projectSubType: "Other",
                    startDate: new Date(), endDate: (new Date()) + 7, wikiUrl: "http://some.url.com", sharePointUrl: "http://some.url.com",
                    technicalManager: "", sponsor: "", description: "", projectNumber: "").save(failOnError: true)

          }

          if (ProjectDashboard.findAllByProject(pr).size() == 0) {
            new ProjectDashboard(overallStatus: "Red", budget: "Green", resources: "Yellow", timeline: "Red",
                    quality: "Red", scope: "Yellow", voc: "Green", project: pr).save(failOnError: true);

          }
        }

        doDevSetup ('test_002')
        doDevSetup ('test_003')
        
        break
      case "production":
        globalSetup();
        break
    }
  }

  def globalSetup = {
    addRoles();
    addAdminUser();
    addGuestUser();
    addPeople();
  }

  def createLists = {
    NamedList.addNewNamedListItem("RYGList", "Red");
    NamedList.addNewNamedListItem("RYGList", "Yellow");
    NamedList.addNewNamedListItem("RYGList", "Green");
  }

  def addRoles = {
    logger.info("Adding Roles")
    def addRole = {rolename ->

      if (Authority.countByAuthority(rolename) == 0) {
        logger.info("Adding Role " + rolename);
        Authority role = new Authority(authority: rolename, description: rolename);
        if (!(role.save(validate: false, flush: true))) {
          role.errors.each {
            logger.error(it)
          }
        } else {
          logger.info("${rolename} added")
        }
      } else {
        logger.info("${rolename} - Skipped Add. Reason: Already Present")
      }
    }
    addRole("ROLE_ADMIN_USER");
    addRole("ROLE_SA_ADMIN");
    addRole("ROLE_SA_USER");
    addRole("ROLE_ALL_READ");
    addRole("ROLE_ALL_DELETE");
    addRole("ROLE_ALL_EDIT");
    addRole("ROLE_SUPER_USER");
  }

  def addGuestUser = {
    logger.info("Adding Guest")
    def userCount = com.portico.security.User.countByUsername("guest");
    if (userCount != null && userCount == 0) {
      com.portico.security.User user = new com.portico.security.User(username: "guest", password: "guest", enabled: true)
      if (!(user.save(validate: false, flush: true))) {
        user.errors.each {
          logger.error(it)
        }
      }
    }
    logger.info("added guest user!!!");
  }

  def addAdminUser = {
    logger.info("Adding Admin Person")
    def userCount = com.portico.security.User.countByUsername("admin");
    if (userCount != null && userCount == 0) {
      com.portico.security.User user = new com.portico.security.User(username: "admin", password: "SolArch123", enabled: true)
      Authority role = Authority.findByAuthority("ROLE_SUPER_USER");
      Authority role1 = Authority.findByAuthority("ROLE_SA_ADMIN");
      Authority role2 = Authority.findByAuthority("ROLE_SA_USER");

      if (!(user.save(validate: false, flush: true))) {
        user.errors.each {
          logger.error(it)
        }
      } else {
        if (role != null) { UserAuthority.create(user, role, true)}
        if (role1 != null) { UserAuthority.create(user, role1, true)}
        if (role2 != null) { UserAuthority.create(user, role2, true)}
      }
      logger.info("added super user!!!");
    }
  }

  def addPeople = {
    def addPerson = {name, email ->
      def cnt = Person.countByEmail(email);
      if (cnt == null || cnt == 0) {
        Person p = new Person(email: email, fullName: name);
        if (!p.save(failOnError: true)) {
          p.errors.each {
            logger.info(it)
          }
        }

      }
    }
    addPerson("Clovis, Michael", "Michael.Clovis@porticosys.com")
    addPerson("Hahn, Nicholas", "Nicholas.Hahn@porticosys.com")
    addPerson("Kumar, Ananda P", "AnandaP.Kumar@porticosys.com")
    addPerson("Shah, Saurin", "Saurin.Shah2@porticosys.com")
    addPerson("Suravarapu, Surya ", "Surya.Suravarapu@porticosys.com")
    addPerson("Viswanath, Veerendra", "Veerendra.Viswanath@porticosys.com")
    addPerson("Weber, Christopher", "Christopher.Weber@porticosys.com")
    addPerson("Wiltz, David", "David.Wiltz@porticosys.com")
    addPerson("Yeluri, Ajay", "Ajay.Yeluri@porticosys.com")
    addPerson("Benkhellat, Yazid", "Yazid.Benkhellat@porticosys.com")
    addPerson("Bruno, Joel", "Joel.Bruno@porticosys.com")
    addPerson("Chandrasekaran, Manikandan", "Manikandan.Chandrasekaran@porticosys.com")

  }

  Closure configureForProduction = {

  }

  Closure configureForDevelopment = {
    //Person ()

  }

  def destroy = {
  }
}
